package com.study.utils;

import com.google.common.collect.EvictingQueue;

/**
 * @author zhuzi
 * 2025/2/13 下午3:33
 */

public class WeighingSystem {
    private final EvictingQueue<Double> readings;
    private final int capacity = 10; // 队列容量，可以根据需要调整
    private final double stabilityThreshold; // 稳定性阈值，决定了什么时候认为数据足够稳定

    public WeighingSystem(double stabilityThreshold) {
        this.readings = EvictingQueue.create(capacity);
        this.stabilityThreshold = stabilityThreshold;
    }

    public void addReading(double reading) {
        readings.add(reading);
        if (isStable()) {
            System.out.println("Vehicle weight: " + calculateWeight());
        }
    }

    private boolean isStable() {
        if (readings.size() < capacity) return false;
        double max = Double.MIN_VALUE, min = Double.MAX_VALUE;
        for (double reading : readings) {
            if (reading > max) max = reading;
            if (reading < min) min = reading;
        }
        return (max - min) <= stabilityThreshold;
    }

    private double calculateWeight() {
        double sum = 0;
        for (double reading : readings) {
            sum += reading;
        }
        return sum / readings.size();
    }

    public static void main(String[] args) {
        WeighingSystem system = new WeighingSystem(0.5); // 设置稳定性阈值为0.5
        // 模拟添加读数
        system.addReading(100.1);
        system.addReading(100.2);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        system.addReading(100.3);
        // ... 继续添加直到系统输出车辆重量
    }
}
